<template>
  <div id='UserEdit'>
    <nav-bar left-arrow left-text="返回" title="编辑资料" @click-left="$router.back()" />
    <cell-group>
      <cell title="头像" center is-link @click="faceRef.click()">
        <template #default>
          <img :src="userInfo.photo" class="user-face" />
          <input type="file" accept="image/*" @change="onFileChange" v-show="false" ref="faceRef" />
        </template>
      </cell>
      <cell title="昵称" :value="userInfo.name" is-link @click="nameDialogShow = true" />
      <cell title="生日" :value="userInfo.birthday" is-link @click="birthdayShow = true" />
    </cell-group>
    <van-dialog v-model:show="nameDialogShow" title="修改用户名" show-cancel-button @confirm="submitName">
      <van-field v-model.trim="editName" :maxlength="7" input-align="center" placeholder="请输入用户名" />
    </van-dialog>
    <van-popup v-model:show="birthdayShow" position="bottom">
      <datetime-picker v-model="currentDate" type="date" title="选择年月日" :min-date="minDate" :max-date="maxDate"
        @cancel="birthdayShow = false" @confirm="submitBirthday" />
    </van-popup>
  </div>
</template>

<script  setup>
import { NavBar, Icon as vanIcon, CellGroup, Cell, Dialog, Field as vanField, Toast, DatetimePicker, Popup as vanPopup } from 'vant'
import { getUserInfo, editUserProfile, editUserAvatar } from '@/api'
import { ref, defineEmits } from 'vue'
const userInfo = ref({})
const VanDialog = Dialog.Component
const nameDialogShow = ref(false)

const emits = defineEmits(['get-user-info'])

// 获取基本信息
const getUserInfoFun = async () => {
  try {
    const { data: { data: info } } = await getUserInfo()
    userInfo.value = info
  } catch {
    console.log('获取用户信息失败')
  }
}
getUserInfoFun()

// 编辑头像
const faceRef = ref(null)
const onFileChange = (e) => {
  const files = e.target.files
  if (files.length === 0) return false
  const reader = new FileReader()
  reader.readAsDataURL(files[0])
  reader.onload = async () => {
     try {
        Toast.loading({
          message: '上传中...',
          forbidClick: true,
          duration: 0
        })
        const { data } = await editUserAvatar(reader.result)
        if (data.message === 'OK') {
          userInfo.value.photo = reader.result
          Toast.clear()
          Toast('修改成功')
        }
      } catch {
        Toast.clear()
        Toast('修改失败')
      }
  }
}

// 编辑生日
const birthdayShow = ref(false)
const minDate = new Date(1900, 1, 1)
const maxDate = new Date()
const currentDate = ref(new Date())
const submitBirthday = async () => {
  const birthday = currentDate.value.toLocaleDateString()
  // 把birthday中的日期改为yyyy-MM-dd格式
  const birthdayReg = /(\d{4})-(\d{1,2})-(\d{1,2})/
  const birthdayStr = birthday.replace(birthdayReg, '$1-$2-$3')
  try {
    const { data } = await editUserProfile({ birthday: birthdayStr })
    if (!data.message) return
    Toast.success('修改成功')
    birthdayShow.value = false
    userInfo.value.birthday = birthdayStr
    emits('get-user-info')
  } catch {
    Toast.fail('修改失败')
  }
}

// 编辑用户名
const editName = ref('')
const submitName = async () => {
  if (!editName.value) {
    Toast('请输入用户名')
    return
  }
  try {
    await editUserProfile({ name: editName.value })
    Toast.success('修改成功')
    nameDialogShow.value = false
    userInfo.value.name = editName.value
    emits('get-user-info')
  } catch {
    Toast.fail('修改失败')
  }
}

</script>

<style lang='less'>
.user-face {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 10px;
}
</style>
